const chalk = require('chalk');
const fs = require('fs');
const inquirer = require('inquirer');
const paths = require('path');
const pxtorem = require('./pxToRem');
const reg = /^.*\.(svg|jpg|jpeg|gif|png|ico|mov|ttf|eot|woff)$/i; // 校验图片格式
const media = ['svg', 'jpg', 'jpeg', 'gif', 'png', 'ico', 'mov', 'ttf', 'eot', 'woff'];
const cssArr = ['.css', '.less', '.scss', '.vue']; // css文件类型
class File {
    constructor() {
        let self = this;
        // 获取文件夹下的所有文件
        this.getFileList = (path) => {
            let filesList = [];
            self.getAllFile(path, filesList);
            return filesList;
        };
        // 文件夹下所有文件
        this.getAllFile = (path, filesList) => {
            let files = fs.readdirSync(path);
            files.forEach(function (item, index) {
                const stat = fs.statSync(path + item);
                if (stat.isDirectory()) {
                    if (item != 'node_modules' && item != '.git') {
                        self.getAllFile(path + item + '/', filesList);
                    }
                } else {
                    filesList.push({
                        path: path,
                        filename: item,
                    })
                }
            })
        }
        //获取文件夹下的所有图片
        this.getImageFiles = (path) => {
            const imgObj = {
                imgPathList: [],
                imgNamesArr: []
            }
            // 过滤出所有图片
            self.getFileList(path).forEach((item) => {
                if (reg.test(item.filename)) {
                    imgObj.imgPathList.push(item.path + item.filename);
                    imgObj.imgNamesArr.push(item.filename);
                }
            });
            return imgObj;
        }
        // 输入单个图片
        this.getSingleImg = (path) => {
            let promps = [],
                chooses = self.getImageFiles(path).imgPathList || [];
            promps.push({
                type: 'rawlist',
                name: 'imgName',
                choices: chooses,
                message: '请选择需要上传图片',
                pageSize: 20
            })
            inquirer.prompt(promps).then(function(answers) {
                console.log(answers)
                // console.log(chalk.green(JSON.stringify(`您输入的文件名：${answers.imgName}`)));
                // self.singleUpload(`${process.cwd()}/${answers.imgName}`, answers.imgName);
            })
        }
        // 选择多个图片上传
        this.getMoreImg = (path) => {
            const self = this;
            let promps = [],
                chooses =  self.getImageFiles(path).imgNamesArr || [];
            // 图片多选命令
            promps.push({
                type: 'checkbox',
                name: 'imgNames',
                message: '请选择上传的图片名称（支持多选）',
                choices: chooses,
                pageSize: 20
            });
            inquirer.prompt(promps).then(function(answers) {
                if (!answers.imgNames.length) {
                    console.log(chalk.red('请重新输入命令，选择图片！！！'));
                    return;
                }
                console.log(answers)
            })
        };
        // 上传所有图片
        this.getAllImg = path => {
            const chooses = self.getImageFiles(path).imgPathList || [];
            chooses.forEach(val=>{
                console.log(val)
            })
        }
        // css文件单选
        this.getSingleCss = path => {
            let promps = [],
                choices = self.getCssFiles(path).cssPathList || [];
            promps.push({
                type: 'rawlist',
                name: 'cssName',
                message: '请选择需要转换的css/less/scss/vue文件',
                choices: choices,
                pageSize: 20
            })
            inquirer.prompt(promps).then(function (answers) {
                self.pxConvertRem(`${answers.cssName}`);
            })
        };
        // 过滤css文件
        this.getCssFiles = path => {
            const cssObj = {
                cssNamesArr: [], // 文件名列表
                cssPathList: []  // 路径列表
            };
            self.getFileList(path).forEach(val => {
                if (cssArr.includes(paths.extname(val.filename))) {
                    cssObj.cssNamesArr.push(val.filename)
                    cssObj.cssPathList.push(val.path + val.filename)
                }
            });
            return cssObj;
        }
        // css文件  多选
        this.getMoreCss = (path) => {
            let promps = [],
                choices = self.getCssFiles(path).cssPathList || [];
            // 文件多选命令
            promps.push({
                type: 'checkbox',
                name: 'cssNames',
                message: '请选择需要转换的文件名称（支持多选）',
                choices: choices,
                pageSize: 20
            })
            inquirer.prompt(promps).then(answers => {
                if (answers.cssNames.length == 0) {
                    console.log(chalk.red('请重新输入命令，选择要转换的文件！！！'));
                    return;
                }
                answers.cssNames.forEach(val => {
                    self.pxConvertRem(`${val}`);
                })
            })
        };
        // css全部
        this.getAllCss = (path) => {
           const allcss = self.getCssFiles(path);
            allcss.cssPathList.forEach(val => {
                self.pxConvertRem(`${val}`);
            });
        }
        // css转换
        this.pxConvertRem = (filePath = '') => {
            let content = fs.readFileSync(filePath, 'utf8');
            if (process.argv[3] == 'add') {
                fs.writeFileSync(filePath, pxtorem.changePx(content));
            } else {
                fs.writeFileSync(filePath, pxtorem.changeRem(content));
            }
            console.log(chalk.green('convert sucess!!!'));
        }
    }
}
module.exports = new File();
